package com.sdruixinggroup.mondayb2b.ui.fragments;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.sdruixinggroup.mondayb2b.API.API;
import com.sdruixinggroup.mondayb2b.R;
import com.sdruixinggroup.mondayb2b.adapter.AreaAdapter;
import com.sdruixinggroup.mondayb2b.adapter.CityAdapter;
import com.sdruixinggroup.mondayb2b.adapter.ProvinceAdapter;
import com.sdruixinggroup.mondayb2b.adapter.QuickAdapter;
import com.sdruixinggroup.mondayb2b.interfaces.ObjectCallBack;
import com.sdruixinggroup.mondayb2b.models.Area;
import com.sdruixinggroup.mondayb2b.models.OpenAreas;
import com.sdruixinggroup.mondayb2b.models.Province;
import com.sdruixinggroup.mondayb2b.ui.Activities.OpenAreaActivity;
import com.sdruixinggroup.mondayb2b.utils.UserInfoUtil;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by 00029935 on 2017/12/4.
 */

public class CityListFragment extends BaseFragment {
    @BindView(R.id.ib_back)
    ImageView ibBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.rv_province)
    RecyclerView rvProvince;
    @BindView(R.id.rv_city)
    RecyclerView rvCity;
    @BindView(R.id.rv_area)
    RecyclerView rvArea;

    @BindView(R.id.ll_location)
    LinearLayout locationLl;
    @BindView(R.id.tv_location)
    TextView tvLocation;

    private ProvinceAdapter provinceAdapter;
    private ArrayList<Province.RegionsBean> province;
    private List<Province.RegionsBean> citis;
    private CityAdapter cityAdapter;
    private AreaAdapter areaAdapter;
    private List<Province.RegionsBean> ares;
    private Province.RegionsBean myProvince;
    private Province.RegionsBean myCity;
    private Province.RegionsBean myArea;

    @Override
    protected int getInflateLayout() {
        return R.layout.city_list_fragment;
    }

    private int type;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        type = getActivity().getIntent().getIntExtra("type", 0);
    }

    @Override
    protected void setUpView(View view) {
        if(type==0) {
            tvTitle.setText("选择城市");
        }else {
            tvTitle.setText("区域选择");
        }
        tvRight.setText("确定");
        tvRight.setVisibility(View.VISIBLE);
        tvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null == myProvince) {
                    showMsgToast("请选择省");
                    return;
                }

                if (null == myCity) {
                    showMsgToast("请选择市");
                    return;
                }

                if (null == myArea) {
                    showMsgToast("请选择区或县");
                    return;
                }

                Intent intent = new Intent();
                intent.putExtra("Province", myProvince);
                intent.putExtra("City", myCity);
                intent.putExtra("Area", myArea);
                if (type == 0) {
                    getActivity().setResult(Activity.RESULT_OK, intent);
                    getActivity().finish();
                } else {
                    intent.setClass(getActivity(), OpenAreaActivity.class);
                    startActivity(intent);
                }

            }
        });

        if (type != 0) {
            locationLl.setVisibility(View.VISIBLE);
            queryData(true);
        } else {
            locationLl.setVisibility(View.GONE);
        }

        provinceAdapter = new ProvinceAdapter();
        province = new ArrayList<>();
        provinceAdapter.setData(province);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvProvince.setLayoutManager(linearLayoutManager);
        rvProvince.setAdapter(provinceAdapter);
        provinceAdapter.setOnItemClickListener(new QuickAdapter.OnItemClickListener<Province.RegionsBean>() {
            @Override
            public void OnItemClick(Province.RegionsBean data, int postion) {


                for (Province.RegionsBean regionsBean : province) {
                    if (regionsBean.getId() == data.getId()) {
                        regionsBean.isSelector = true;
                    } else {
                        regionsBean.isSelector = false;
                    }
                }
                myProvince = data;
                provinceAdapter.reflashData(province);
                queryDate(data.getId(), 2);
                ares = new ArrayList<>();
                if(areaAdapter!=null){
                    areaAdapter.reflashData(ares);
                }
            }
        });


        citis = new ArrayList<>();
        cityAdapter = new CityAdapter();
        cityAdapter.setData(citis);
        LinearLayoutManager linearLayoutManager1 = new LinearLayoutManager(getContext());
        linearLayoutManager1.setOrientation(LinearLayoutManager.VERTICAL);
        rvCity.setLayoutManager(linearLayoutManager1);
        rvCity.setAdapter(cityAdapter);

        cityAdapter.setOnItemClickListener(new QuickAdapter.OnItemClickListener<Province.RegionsBean>() {
            @Override
            public void OnItemClick(Province.RegionsBean data, int postion) {
                for (Province.RegionsBean regionsBean : citis) {
                    if (regionsBean.getId() == data.getId()) {
                        regionsBean.isSelector = true;
                    } else {
                        regionsBean.isSelector = false;
                    }
                }
                myCity = data;
                cityAdapter.reflashData(citis);
                queryDate(data.getId(), 3);
            }
        });

        areaAdapter = new AreaAdapter();
        ares = new ArrayList<>();
        areaAdapter.setData(ares);
        LinearLayoutManager linearLayoutManager2 = new LinearLayoutManager(getContext());
        linearLayoutManager2.setOrientation(LinearLayoutManager.VERTICAL);
        rvArea.setLayoutManager(linearLayoutManager2);
        rvArea.setAdapter(areaAdapter);
        areaAdapter.setOnItemClickListener(new QuickAdapter.OnItemClickListener<Province.RegionsBean>() {
            @Override
            public void OnItemClick(Province.RegionsBean data, int postion) {
                for (Province.RegionsBean regionsBean : ares) {
                    if (regionsBean.getId() == data.getId()) {
                        regionsBean.isSelector = true;
                    } else {
                        regionsBean.isSelector = false;
                    }
                }
                myArea = data;
                areaAdapter.reflashData(ares);
            }
        });
        queryDate(0, 1);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @OnClick(R.id.ib_back)
    public void onClick() {
        getActivity().finish();
    }


    /**
     * 1 , 2,3
     *
     * @param parent_id
     */
    private void queryDate(int parent_id, final int level) {
        String url = API.MEMBER_ADDRESSES_REGIONS_PARENT + parent_id;

        HashMap<String, String> header = new HashMap<>();
        header.put("Accept", "*/*");
        if(type!=0){
            url+="&open_status=1";
        }

        TypeToken<Province> typeToken = new TypeToken<Province>() {
        };
        OkHttpUtils.get().headers(header).url(url).build().execute(new ObjectCallBack<Province>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(Province response, int id) {
                if (null != response) {
                    if (response.getErr_code() == 0) {
                        List<Province.RegionsBean> data = response.getRegions();
                        switch (level) {
                            case 1:
                                province.addAll(data);
                                provinceAdapter.reflashData(province);
                                break;
                            case 2:
                                citis.clear();
                                if (null != data && !data.isEmpty()) {
                                    citis.addAll(data);
                                }
                                cityAdapter.reflashData(citis);
                                break;
                            case 3:
                                ares.clear();
                                if (null != data && !data.isEmpty()) {
                                    ares.addAll(data);
                                }
                                areaAdapter.reflashData(ares);
                                break;
                        }

                    } else {
                        showMsgToast(response.getErr_msg());
                    }
                }
            }
        });

    }


    private void queryData(final Boolean isReflush) {

        final String url = API.AREA + UserInfoUtil.getInfoToken(getContext()) + "&longitude=" + UserInfoUtil.mLongitude + "&latitude=" + UserInfoUtil.mLatitude;
        HashMap<String, String> heades = new HashMap<>();
        heades.put("Accept", "*/*");

        TypeToken<Area> typeToken = new TypeToken<Area>() {
        };

        OkHttpUtils.get().url(url).headers(heades).build().execute(new ObjectCallBack<Area>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {
            }

            @Override
            public void onResponse(Area response, int id) {

                if (null != response) {
                    if (response.err_code == 0) {
                        if(response.county==null&&response.city==null&&response.province==null){
//                            ivLocation.setImageResource(R.mipmap.order_location);
//                            tvLocation.setText("暂无定位");
                        }else {
//                            String msg="";
//                            if(response.area==null){
//                                msg+="(暂无区域) ";
//                            }else {
//                                msg+="("+response.area.name+") ";
//                            }
//                            msg+=response.province.name+" "+response.city.name+" "+response.county.name;
//                            tvLocation.setText(msg);
                            locationLl.setVisibility(View.VISIBLE);
                        }

                    } else {
                        showMsgToast(response.err_msg);
                    }
                }

            }
        });

    }
}
